package newtank.network.client.handler;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import newtank.TankClientFrame;
import newtank.view.context.EnvironmentContext;
import newtank.view.context.TankViewContext;
import server.GpcRequest;
import server.netty.GpcDataPackage;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lijiahao
 * @since 2022/1/28
 */
@AllArgsConstructor
public class EnvironmentDataHandler implements DataHandler<EnvironmentContext> {

    private final TankClientFrame tankClientFrame;
    private final Map<String, Boolean> registries =  new HashMap<>();

    @Override
    public EnvironmentContext decodePackage(GpcDataPackage gpcDataPackage) {
        GpcRequest gpcRequest = gpcDataPackage.getRouteRequest();
        EnvironmentContext environmentContext = new EnvironmentContext();
        environmentContext.setSelfUnique(gpcRequest.getHeader("UNIQUE"));
        String context = gpcRequest.getHeader("TANK_CONTEXT");
        environmentContext.setAllTankViewContexts(JSONObject.parseArray(context, TankViewContext.class));
        return environmentContext;
    }

    @Override
    public void handle(GpcDataPackage gpcDataPackage) {
        EnvironmentContext environmentContext = decodePackage(gpcDataPackage);
        List<TankViewContext> newTanks = environmentContext.getAllTankViewContexts()
                .stream()
                .filter(tank -> registries.getOrDefault(tank.getTankId(), Boolean.TRUE))
                .collect(Collectors.toList());
        if(newTanks.size() > 0) {
            newTanks.forEach(tank -> {
                registries.put(tank.getTankId(), Boolean.FALSE);
            });
            tankClientFrame.getTankViewContexts().addAll(newTanks);
            if(tankClientFrame.getDynamicSelfUnique() == null) {
                tankClientFrame.setDynamicRegistryId(environmentContext.getSelfUnique());
                for(TankViewContext tankViewContext: environmentContext.getAllTankViewContexts()) {
                    if(tankViewContext.getTankId().startsWith(environmentContext.getSelfUnique())) {
                        tankClientFrame.setSelfTankContext(tankViewContext);
                        break;
                    }
                }
                tankClientFrame.initFrame();
            } else {
                tankClientFrame.addPaintViews(newTanks);
            }
        }
    }

    @Override
    public boolean support(GpcDataPackage gpcDataPackage) {
        return gpcDataPackage != null && gpcDataPackage.getCode() == 1;
    }
}
